package com.kaiji.mq.send;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 发送方
 * @author 开机
 * @since 2018-03-22
 */
public class Sender {

	private static final Logger __logger = LoggerFactory.getLogger(Sender.class);
	private static final String USER_NAME = null;
	private static final String PASSWORD = null;
	private static final String TCP = "tcp://localhost:61616";
	
	
	public static void main(String[] args) {
		
		// 连接JMS的工厂
		ConnectionFactory cf = null;
		// 工厂创建的连接JMS对象
		Connection connection = null;
		// 发送和接收消息的 线程
		Session session = null;
		// 消息的接收者
		Destination destination = null; 
		// 消息创建者
		MessageProducer messageProducer = null; 
		
		__logger.info("连接JMS的用户是: {}--密码是: {}--协议是: {}", USER_NAME, PASSWORD, TCP);
		// 第一步： 创建工厂
		cf = new ActiveMQConnectionFactory(USER_NAME, PASSWORD, TCP);
		try {
			// 构造从工厂得到连接对象
			connection = cf.createConnection();
			connection.start();
			__logger.info("JMS启动成功~~~！");
			
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			
			// 创建 消息接收者  kaiji队列
			destination = session.createQueue("kaijiQuene");
			// 得到消息  生成发送者
			messageProducer = session.createProducer(destination);
			// 设置消息 不持久化
			messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			
			// 构造函数发送消息
			sendMessage(session, messageProducer);
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}


	private static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
		for (int i = 0; i < 5; i++) {
			TextMessage tm = session.createTextMessage("这是我要发送的消息！次数是： " + i);
			__logger.info("发送的消息是： {}", tm.getText());
			messageProducer.send(tm);
		}
	}
}
